package com.ylbh.modules.balancelog.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylbh.common.exception.NormalException;
import com.ylbh.common.pojo.balancelog.dto.UserBalanceMoneyDTO;
import com.ylbh.common.pojo.balancelog.dto.ShoppingCommissionDTO;
import com.ylbh.common.pojo.balancelog.vo.BalanceLogVO;
import com.ylbh.common.pojo.member.dto.select.RevenueLogSelectDTO;
import com.ylbh.common.utils.ExcelUtils;
import com.ylbh.common.utils.IdWorker;
import com.ylbh.common.utils.ShiroUtils;
import com.ylbh.modules.balancelog.entity.ShoppingBalanceLog;
import com.ylbh.modules.balancelog.mapper.ShoppingBalanceLogMapper;
import com.ylbh.modules.balancelog.service.ShoppingBalanceLogService;
import com.ylbh.modules.business.entity.ShoppingUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylbh.common.utils.PageUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service("shoppingBalanceLogService")
public class ShoppingBalanceLogServiceImpl extends ServiceImpl<ShoppingBalanceLogMapper, ShoppingBalanceLog> implements ShoppingBalanceLogService {

    @Autowired
    private ShoppingBalanceLogMapper shoppingBalanceLogMapper;

    /**
     * 余额变动
     * @param pageDTO
     * @return
     */
    @Override
    public PageUtils queryBalanceLogList(RevenueLogSelectDTO pageDTO) {
        Page<Integer> page = new Page<>(pageDTO.getPage(), pageDTO.getLimit());
        String lastStart = null;
        String lastEnd = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != pageDTO.getLastStart())
            lastStart = sdf.format(pageDTO.getLastStart());
        if (null != pageDTO.getLastEnd())
            lastEnd = sdf.format(pageDTO.getLastEnd());
        List<BalanceLogVO> list = shoppingBalanceLogMapper.selectBalanceLogList(lastStart, lastEnd, pageDTO.getKeywords(), page);
        return new PageUtils(new Page<BalanceLogVO>().setTotal(page.getTotal()).setRecords(list));
    }

    @Override
    public String modifyUserCommissionMoney(UserBalanceMoneyDTO userBalanceMoneyDTO) {
        // 查询用户当前的佣金
        BigDecimal commissionMoney = shoppingBalanceLogMapper.selectUserCommissionMoney(userBalanceMoneyDTO.getName());
        ShoppingUser user = shoppingBalanceLogMapper.selectIdByUserName(userBalanceMoneyDTO.getName());
        ShoppingBalanceLog log = new ShoppingBalanceLog();
        if (!StringUtils.isEmpty(userBalanceMoneyDTO.getName())) {
            if (userBalanceMoneyDTO.getType() == 1) {
                // 当前的减去扣除的
                int surplus = commissionMoney.compareTo(userBalanceMoneyDTO.getNum());
                if (surplus == 0 || surplus == 1) {
                    // 表示扣除后的佣金大于等于0，则可以继续执行

                    // 表示扣除用户的佣金
                    BigDecimal subtract = commissionMoney.subtract(userBalanceMoneyDTO.getNum());
                    // 修改当前用户的用户信息
                    shoppingBalanceLogMapper.updateUserCommissionMoney(userBalanceMoneyDTO.getName(), subtract);

                    // 增加余额变动记录
                    log.setBalanceId(new IdWorker().nextId());
                    log.setCreateTime(new Date());
                    log.setUserId(user.getId().intValue());
                    log.setUserType(user.getUserType());
                    log.setChangeType(13);
                    log.setBalanceType(0);
                    log.setPassiveUserId(33307);
                    log.setPassiveUserType(1);
                    log.setChangeRemark(userBalanceMoneyDTO.getRemark());
                    log.setChangeBalance(userBalanceMoneyDTO.getNum());
                    log.setCreateUserId(ShiroUtils.getUserId().intValue());
                    log.setState(1);
                    log.setLogType(1);
                    log.setCurrentBalance(subtract);
                    shoppingBalanceLogMapper.insert(log);

                } else {
                    return "当前用户佣金余额不足";
                }
            } else if (userBalanceMoneyDTO.getType() == 0) {
                // 给用户加佣金
                BigDecimal subtract = commissionMoney.add(userBalanceMoneyDTO.getNum());
                // 修改当前用户的用户信息
                shoppingBalanceLogMapper.updateUserCommissionMoney(userBalanceMoneyDTO.getName(), subtract);

                // 增加余额变动记录
                log.setBalanceId(new IdWorker().nextId());
                log.setCreateTime(new Date());
                log.setUserId(user.getId().intValue());
                log.setUserType(user.getUserType());
                log.setChangeType(13);
                log.setBalanceType(1);
                log.setPassiveUserId(33307);
                log.setPassiveUserType(1);
                log.setChangeRemark(userBalanceMoneyDTO.getRemark());
                log.setChangeBalance(userBalanceMoneyDTO.getNum());
                log.setCreateUserId(ShiroUtils.getUserId().intValue());
                log.setState(1);
                log.setLogType(1);
                log.setCurrentBalance(subtract);
                shoppingBalanceLogMapper.insert(log);

                // 增加佣金变动记录
                ShoppingCommissionDTO commissionDTO = new ShoppingCommissionDTO();
                commissionDTO.setCommissionId(new IdWorker().nextId());
                commissionDTO.setUserId(33307);
                commissionDTO.setRecommId(user.getId().intValue());
                commissionDTO.setCommissionType(9);
                commissionDTO.setCommissionMoney(userBalanceMoneyDTO.getNum());
                commissionDTO.setRecommUserType(user.getUserType());
                commissionDTO.setGoodsProfits(userBalanceMoneyDTO.getNum());
                commissionDTO.setGoodsPrice(userBalanceMoneyDTO.getNum());
                commissionDTO.setCreateTime(new Date());
                commissionDTO.setCommissionMessage(userBalanceMoneyDTO.getRemark());
                shoppingBalanceLogMapper.insertCommission(commissionDTO);
            }
            return "操作成功";
        }
        return "操作失败";
    }

    /**
     * 查询用户当前的佣金
     * @param name
     * @return
     */
    @Override
    public BigDecimal getCommissionMoneyByUserName(String name) {
        return shoppingBalanceLogMapper.selectUserCommissionMoney(name);
    }

    /**
     * 系统管理余额记录
     * @param dto
     * @return
     */
    @Override
    public PageUtils queryAdminAndBalanceLog(RevenueLogSelectDTO dto) {
        Page<Integer> page = new Page<>(dto.getPage(), dto.getLimit());
        List<BalanceLogVO> list = shoppingBalanceLogMapper.selectAdminAndBalanceLog(dto, page);
        return new PageUtils(new Page<BalanceLogVO>().setTotal(page.getTotal()).setRecords(list));
    }

    /**
     * 余额变动导出
     * @param request
     * @param response
     */
    @Override
    public void balanceRecordExcel(HttpServletRequest request, HttpServletResponse response) throws NormalException {
        List<BalanceLogVO> list = shoppingBalanceLogMapper.selectBalanceRecordExcel(request.getParameter("startTime"), request.getParameter("endTime"), request.getParameter("keywords"));
        ExcelUtils.exportExcel(list, "余额变动", "", BalanceLogVO.class, System.currentTimeMillis() + ".xls", response);
    }
}
